package com.zaoniao.enstudy.api.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.zaoniao.enstudy.domain.entity.User;
import com.zaoniao.enstudy.domain.service.UserService;
import com.zaoniao.enstudy.infracore.web.BaseResponse;
import com.zaoniao.enstudy.infracore.web.DataResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://api.weixin.qq.com/sns/jscode2session?appid=wx9b09ba285c83304e&secret=71fbd5fb70b5f70240b2c53cc20f4518&grant_type=authorization_code&js_code=1">.
 * 小程序登录..
 * </a>
 * 用户相关接口Api.
 */
@RestController
@Tag(name = "用户相关接口Api")
@RequestMapping("/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {

    private final WxMaService wxMaService;

    private final UserService userService;

    /**
     * <a href="https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html">
     * 小程序登录文档
     * </a>
     *
     * @param code          登录凭证
     * @param encryptedData 微信服务提供的隐藏数据
     * @param iv            偏移向量
     * @return -
     * @throws WxErrorException 微信授权异常
     */
    @Operation(summary = "获取微信授权登录", description = "小程序登录专用")
    @GetMapping("/wechat-login")
    public BaseResponse wechatSession(@Parameter(name = "code", description = "wx.login获得临时登录凭证code")
                                      @RequestParam(value = "code") String code,
                                      @Parameter(name = "encryptedData", description = "wx.getUserInfo接口获得隐藏数据encryptedData")
                                      @RequestParam(value = "encryptedData") String encryptedData,
                                      @Parameter(name = "iv", description = "wwx.getUserInfo接口获得偏移向量iv")
                                      @RequestParam(value = "iv") String iv) throws WxErrorException {
        // 调用微信 API 获取用户的 openid 和 session_key
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
        String openid = session.getOpenid();

        // 调用微信 API 获取用户的手机号 需要企业资质
//        WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNumber(code);
//        String phoneNumber = phoneInfo.getPhoneNumber();
        String phoneNumber = "";

        // 调用微信 API 获取用户的详细信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), encryptedData, iv);
        // 获取用户昵称
        String nickName = userInfo.getNickName();
        // 获取用户头像
        String avatarUrl = userInfo.getAvatarUrl();
        // 获取用户国家
        String country = userInfo.getCountry();
        // 获取用户省份
        String province = userInfo.getProvince();
        // 获取用户城市
        String city = userInfo.getCity();

        // 将用户信息保存到数据库中
        User user = User.build(openid, nickName, avatarUrl, country, province, city, phoneNumber);
        userService.saveOrUpdate(user);

        // 返回用户信息
        Map<String, Object> data = new HashMap<>();
        data.put("openid", openid);
        data.put("nickName", nickName);
        data.put("avatarUrl", avatarUrl);
        data.put("country", country);
        data.put("province", province);
        data.put("city", city);
        data.put("phoneNumber", phoneNumber);
        return DataResponse.ok(data);
    }

    // todo
    @Operation(summary = "手机号验证码登录")
    @GetMapping("/mobile-login")
    public BaseResponse loginMobile() {
        return DataResponse.ok();
    }

}
